package com.ruoyi.pay.wx.util;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.pay.domain.PayOrder;
import com.ruoyi.pay.wx.config.WxPayConfig;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.util.PemUtil;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiService;

public class WxPayUtil {

   private static WxPayConfig config = SpringUtils.getBean(WxPayConfig.class);

   private static RSAAutoCertificateConfig wxpayBaseConfig = SpringUtils.getBean(RSAAutoCertificateConfig.class);

   @Autowired
   JsapiService jsapiService;

   // public JSONObject pay(PayOrder payOrder, String prepayId) throws Exception {
   // // 统一下单，生成预支付交易单

   // // 解析返回结果
   // // JSONObject jsonObject = JSON.parseObject(bodyAsString);
   // // System.out.println(jsonObject);

   // // String prepayId = jsonObject.getString("prepay_id");

   // String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
   // String nonceStr = RandomStringUtils.randomNumeric(32);
   // ArrayList<Object> list = new ArrayList<>();
   // list.add(config.getAppId());
   // list.add(timeStamp);
   // list.add(nonceStr);
   // list.add("prepay_id=" + prepayId);
   // // 二次签名，调起支付需要重新签名
   // StringBuilder stringBuilder = new StringBuilder();
   // for (Object o : list) {
   // stringBuilder.append(o).append("\n");
   // }
   // /*
   // * String signMessage = stringBuilder.toString();
   // * byte[] message = signMessage.getBytes();
   // *
   // * Signature signature = Signature.getInstance("SHA256withRSA");
   // * signature.initSign(
   // * PemUtil.loadPrivateKey(new FileInputStream(new
   // * File(config.getPrivateKeyFilePath()))));
   // * signature.update(message);
   // * String packageSign = Base64.getEncoder().encodeToString(signature.sign());
   // */

   // // 构造数据给微信小程序，用于调起微信支付
   // JSONObject jo = new JSONObject();
   // jo.put("timeStamp", timeStamp);
   // jo.put("nonceStr", nonceStr);
   // jo.put("package", "prepay_id=" + prepayId);
   // jo.put("signType", wxpayBaseConfig.getSignType());
   // jo.put("paySign");

   // return jo;

   // // return jsonObject;
   // }

   public static String sign(byte[] message) throws Exception {
      PrivateKey privateKey = PemUtil.loadPrivateKeyFromPath(config.getWxcertPath());
      Signature sign = Signature.getInstance("SHA256withRSA");
      sign.initSign(privateKey);
      sign.update(message);
      return Base64.getEncoder().encodeToString(sign.sign());
   }
}
